﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.RequestModels.Material;
using Ekton_Manage_DTO.RequestModels.User;
using Ekton_Manage_DTO.RequestModels.UserControl;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_Framework.Redis;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using Ekton_Manage_Mapper.EntityMappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Ekton_Manage_Business
{
    public class UserBusiness : IUserBusiness
    {
        private readonly UserListMapper _userListMapper;
        private readonly IBaseRepository<sys_user, int> _basesysUserRepository;
        private readonly IBaseRepository<user_list, int> _ApibasesysUserRepository;
        private readonly SerializeParameter _serialize;
        private readonly IBaseRepository<verify_code, int> _baseverifyCodeRepository;
        private readonly IBaseRepository<msg_user, int> _basemsguserRepository;
        private readonly IBaseRepository<particulars_order, int> _baseparticularsorderRepository;
        public UserBusiness(IBaseRepository<user_list, int> ApibasesysUserRepository, UserListMapper userListMapper, SerializeParameter serialize, IBaseRepository<sys_user, int> basesysUserRepository, IBaseRepository<verify_code, int> baseverifyCodeRepository, IBaseRepository<msg_user, int> basemsguserRepository, IBaseRepository<particulars_order, int> baseparticularsorderRepository)
        {
            _userListMapper = userListMapper;
            _serialize = serialize;
            _basesysUserRepository = basesysUserRepository;
            _ApibasesysUserRepository = ApibasesysUserRepository;
            _baseverifyCodeRepository = baseverifyCodeRepository;
            _basemsguserRepository = basemsguserRepository;
            _baseparticularsorderRepository = baseparticularsorderRepository;
        }
        /// <summary>
        /// 后端登录api接口
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public async Task<sys_user> CheckLogin(string userName, string passWord)
        {
            return await _basesysUserRepository.QuerySingleData(m => m.account == userName && m.password == passWord);
        }
        /// <summary>
        /// 前端用户api接口     
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public async Task<user_list> APICheckLogin(string userName, string passWord)
        {
            return await _ApibasesysUserRepository.QuerySingleData(m => m.account == userName && m.password == passWord);
        }


        /// <summary>
        /// 查询用户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<Tuple<List<user_list>, int>> GetUserList(QueryDataParame query)
        {
            var dicData = await _serialize.ParameConvertToDict(query.parame);
            Expression<Func<user_list, bool>> expression = m => true;
            if (dicData.ContainsKey("name") && !string.IsNullOrEmpty(dicData["name"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.name.Contains(dicData["name"].ToString()));
            }
            if (dicData.ContainsKey("phone") && !string.IsNullOrEmpty(dicData["phone"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.phone.Contains(dicData["phone"].ToString()));
            }
            if (dicData.ContainsKey("company") && !string.IsNullOrEmpty(dicData["company"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.company.Contains(dicData["company"].ToString()));
            }
            if (dicData.ContainsKey("sex") && !string.IsNullOrEmpty(dicData["sex"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.sex == dicData["sex"].ObjToInt());
            }
            if (dicData.ContainsKey("email") && !string.IsNullOrEmpty(dicData["email"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.email.Contains(dicData["email"].ToString()));
            }
            if (dicData.ContainsKey("state") && !string.IsNullOrEmpty(dicData["state"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.state == dicData["state"].ObjToInt());
            }
            if (dicData.ContainsKey("create_op_date") && !string.IsNullOrEmpty(dicData["create_op_date"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.create_op_date >= dicData["create_op_date"].ObjToDate() && m.create_op_date <= dicData["create_op_date"].ObjToDate().AddDays(1));
            }
            var result = await _userListMapper.QueryPageData(query, expression);
            return result;
        }


        /// <summary>
        ///  停用（修改用户状态）
        /// </summary>
        /// <param state="1"></param>
        /// <returns></returns>
        public async Task<Message> PutUserState(int userId)
        {
            var userInfo = await _userListMapper.QuerySingleData(userId);
            if (userInfo.state == 1)
            {
                userInfo.state = 2;//用户停用
            }
            else if (userInfo.state == 2)
            {
                userInfo.state = 1;//取消禁用
            }
            var result = await _userListMapper.UpdateSingleData(userInfo);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Message> InsertUserInfo(DtoUserControl request)
        {
            var userInfo = await _userListMapper.InsertSingleData(new user_list
            {
                account = request.account,
                name = request.name,
                password = request.password,
                sex = request.sex,
                phone = request.phone,
                email = request.email,
                state = request.state,
                company = request.company
            });
            return new Message(userInfo.Item1);
        }
        /// <summary>
        /// 重置密码（修改用户密码为123456）
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<Message> PutUserPwd(int userId)
        {
            var userInfo = await _userListMapper.QuerySingleData(userId);
            if (userInfo is null) return new Message("该用户不存在", false, 202);
            userInfo.password = "123456";
            var result = await _userListMapper.UpdateSingleData(userInfo);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// 
        public async Task<Message> PutUserInfo(DtoUserControl request)
        {
            var userInfo = await _userListMapper.QuerySingleData(request.id);
            if (userInfo == null) return new Message(false,202);
            userInfo.account = request.account;
            userInfo.name = request.name;
            userInfo.password = request.password;
            userInfo.phone = request.phone;
            userInfo.email = request.email;
            userInfo.state = request.state;
            userInfo.sex = request.sex;
            userInfo.company = request.company;
            var result = await _userListMapper.UpdateSingleData(userInfo);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// 
        public async Task<Message> DeleteUserInfo(int userId)
        {
            var usermsgid = new List<int>();
            var userorderid = new List<int>();
            //删除用户信息时删除关于他的消息推送记录
            var usermsg = await _basemsguserRepository.QueryTableList(m => m.user_id == userId);
            foreach (var item in usermsg)
            {
                usermsgid.Add(item.id);
            }
            await _basemsguserRepository.DeleteArray(usermsgid);
            //删除用户信息时删除他的订单记录
            var userorder = await _baseparticularsorderRepository.QueryTableList(m => m.user_id == userId);
            foreach (var item in userorder)
            {
                userorderid.Add(item.id);
            }
            await _baseparticularsorderRepository.DeleteArray(userorderid);
            //最后删除用户信息
            var result = await _userListMapper.DeleteSingleData(userId);
            return new Message(result);
        }

        /// <summary>
        /// 查询用户个人订单记录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// 
        public async Task<user_list> GetUserOrderList(int order_id)
        {
            var userInfo = await _userListMapper.QuerySingleData(order_id);
            return userInfo;
        }

        /// <summary>
        /// 后台用户忘记密码
        /// </summary>
        public async Task<Message> PostUserPwd(DtoUserPwd request)
        {
            var verifyCode = await _baseverifyCodeRepository.QuerySingleData(m => m.email == request.email && m.state == 0);
            var sysUserName = await _basesysUserRepository.QuerySingleData(m => m.account == request.account);
            if (verifyCode is null)
            {
                return new Message("输入的是无效的邮箱或是无效的验证码，请仔细核对", false, 202);
            }
            if (sysUserName is null)
            {
                return new Message("输入的用户名不正确", false, 202);
            }
            else
            {
                if (request.auth_code == verifyCode.code)
                {
                    if (DateTime.Now <= verifyCode.create_op_date.AddMinutes(50))
                    {
                        var sysUser = await _basesysUserRepository.QuerySingleData(m => m.account == request.account && m.email == request.email);
                        if (sysUser is null) return new Message("该用户不存在", false, 202);
                        sysUser.password = request.password;
                        var result = await _basesysUserRepository.UpdateSingleData(sysUser);
                        //修改密码成功后修改验证码状态
                        verifyCode.state = 1;
                        var updateCodeState = await _baseverifyCodeRepository.UpdateSingleData(verifyCode);
                        return new Message(result.Item1);
                    }
                    else
                    {
                        //验证码超时后修改验证码状态
                        verifyCode.state = 1;
                        var updateCodeState = await _baseverifyCodeRepository.UpdateSingleData(verifyCode);
                        return new Message("验证码已超时", false, 202);
                    }
                }
                else
                {
                    return new Message("无效的验证码，请仔细核对", false, 202);
                }
            }
        }
    }
}
